<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
    <title>身体数据记录</title>
    <link rel="stylesheet" href="css/style.css" />
    <script src="js/message.js"></script>
    <script src="js/xlsx.full.min.js"></script>
    <style>
        .header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
        }
        .tab-nav .active {
            background: #007bff;
            color: gold;
        }

        .tab-panel {
            display: none;
            margin-top: 10px;
        }

        .tab-panel.active {
            display: block;
        }

        .toolbar {
            display: flex;
            justify-content: space-between;
            margin-bottom: 15px;
            align-items: center;
        }
        #year-select {
            padding: 8px;
            border-radius: 4px;
            border: 1px solid #68768a;
            background: rgba(53, 75, 105, 0.5);
            color: #cfe2f3;
            outline: none;
        }
        #add-data-btn {
            width: 40px;
            height: 40px;
            font-size: 20px;
            border-radius: 50%;
            background: #007bff;
            color: white;
            border: none;
            cursor: pointer;
        }
        .data-table {
            width: 100%;
            border-collapse: collapse;
            font-size: 14px;
        }
        .data-table th, .data-table td {
            border: 1px solid #68768a;
            padding: 8px;
            text-align: center;
        }
        .data-table th {
            background: rgba(53, 75, 105, 0.5);
        }
        .data-table .delete-row {
            color: #e74c3c;
            cursor: pointer;
        }
    </style>
</head>
<body>
<!-- 身体数据页面 -->
<div id="body-data-page" class="container">
    <div class="header">
        <h2>身体数据记录</h2>
        <div class="nav-right">
            <button class="nav-right-button" id="exportAll" onclick="exportExcel()">导出全部</button>
            <button class="nav-right-button" id="clearAll" onclick="clearData()">清空全部</button>
        </div>
    </div>

    <div class="body-content">
        <!-- 工具栏 -->
        <div class="toolbar">
            <select id="year-select"></select>
            <button id="add-data-btn" class="btn-primary">+</button>
        </div>

        <!-- 数据表格 -->
        <div id="data-tab" class="tab-panel active">
            <table class="data-table">
                <thead>
                <tr>
                    <th>日期</th>
                    <th>体重 (kg)</th>
                    <th>胸围 (cm)</th>
                    <th>臂围 (cm)</th>
                    <th>腰围 (cm)</th>
                    <th>臀围 (cm)</th>
                    <th>大腿围 (cm)</th>
                    <th>小腿围 (cm)</th>
                    <th>操作</th>
                </tr>
                </thead>
                <tbody id="data-table-body"></tbody>
            </table>
        </div>
    </div>
</div>

<!-- 添加数据弹窗 -->
<div id="add-data-modal" class="modal hidden">
    <div class="modal-content">
        <span class="close-btn">&times;</span>
        <h3>设置身体数据</h3>
        <form id="add-data-form">
            <label>日期：</label>
            <input type="date" id="data-date" required />
            <input type="hidden" id="edit-index"/>
            <label>体重 (kg)：</label>
            <input type="number" id="weight" step="0.01" min="0" value="0" />
            <div style="display: flex;">
                <label>胸围(cm)：</label>
                <input type="number" id="chest" step="0.1" min="0" value="0" style="width: 170px;margin-right: 24px;"/>
                <label>臂围(cm)：</label>
                <input type="number" id="arm" step="0.1" min="0" value="0" style="width: 170px;"/>
            </div>
            <div style="display: flex;">
                <label>腰围(cm)：</label>
                <input type="number" id="waist" step="0.1" min="0" value="0" style="width: 170px;margin-right: 24px;"/>
                <label>臀围(cm)：</label>
                <input type="number" id="hip" step="0.1" min="0" value="0" style="width: 170px;"/>
            </div>
            <div style="display: flex;">
                <label>大腿(cm)：</label>
                <input type="number" id="thigh" step="0.1" min="0" value="0" style="width: 170px;margin-right: 24px;"/>
                <label>小腿(cm)：</label>
                <input type="number" id="calf" step="0.1" min="0" value="0" style="width: 170px;"/>
            </div>
            <div style="text-align: center; margin-top: 20px;">
                <button class="modal-button" type="submit" style="width: 100%;">保存</button>
            </div>
        </form>
    </div>
</div>

<script>
    const BODY_DATA_KEY = 'bodyData';
    let editing = false; // 是否是编辑
    /**
     * 初始化年份选择器
     */
    function initYearSelect() {
        const select = document.getElementById('year-select');
        const currentYear = new Date().getFullYear();
        for (let i = currentYear - 3; i <= currentYear + 1; i++) {
            const option = document.createElement('option');
            option.value = i;
            option.text = i + ' 年';
            select.appendChild(option);
        }
        select.value = currentYear;
        select.onchange = renderDataTable;
    }
    /**
     * 获取数据
     */
    function getBodyData() {
        const data = localStorage.getItem(BODY_DATA_KEY);
        return data ? JSON.parse(data) : [];
    }
    /**
     * 将数据保存到localStorage中
     */
    function saveBodyData(data) {
        // 按日期排序升序
        const sortedData = data.sort((a, b) => new Date(a.date) - new Date(b.date));
        localStorage.setItem(BODY_DATA_KEY, JSON.stringify(data));
    }

    /**
     * 获取最后一条数据
     */
    function getLastEntry() {
        const data = getBodyData().sort((a, b) => new Date(b.date) - new Date(a.date));
        return data[0] || null;
    }
    /**
     * 打开新增弹窗
     */
    function openAddModal() {
        editing = false;
        const last = getLastEntry();
        const today = new Date().toISOString().split('T')[0];
        document.getElementById('data-date').value = today;
        document.getElementById('weight').value = last ? last.weight : 0;
        document.getElementById('chest').value = last ? last.chest : 0;
        document.getElementById('arm').value = last ? last.arm : 0;
        document.getElementById('waist').value = last ? last.waist : 0;
        document.getElementById('hip').value = last ? last.hip : 0;
        document.getElementById('thigh').value = last ? last.thigh : 0;
        document.getElementById('calf').value = last ? last.calf : 0;
        document.getElementById('add-data-modal').classList.remove('hidden');
    }
    /**
     * 根据索引打开编辑弹窗并填充数据
     */
    function openEditModal(index) {
        editing = true;
        const data = getBodyData();
        const item = data[index];
        document.getElementById('edit-index').value = index;
        document.getElementById('data-date').value = item.date;
        document.getElementById('weight').value = item.weight;
        document.getElementById('chest').value = item.chest;
        document.getElementById('arm').value = item.arm;
        document.getElementById('waist').value = item.waist;
        document.getElementById('hip').value = item.hip;
        document.getElementById('thigh').value = item.thigh;
        document.getElementById('calf').value = item.calf;
        document.getElementById('add-data-modal').classList.remove('hidden');
    }
    // 保存按钮提交事件
    document.getElementById('add-data-form').onsubmit = function (e) {
        e.preventDefault();
        const entry = {
            date: document.getElementById('data-date').value,
            weight: parseFloat(document.getElementById('weight').value),
            chest: parseFloat(document.getElementById('chest').value),
            arm: parseFloat(document.getElementById('arm').value),
            waist: parseFloat(document.getElementById('waist').value),
            hip: parseFloat(document.getElementById('hip').value),
            thigh: parseFloat(document.getElementById('thigh').value),
            calf: parseFloat(document.getElementById('calf').value)
        };
        const data = getBodyData();
        // 如果是编辑的话，则根据索引更改对应的数据，如果是新增则直接push
        if (editing){
            let editIndex = document.getElementById('edit-index').value;
            data[editIndex] = entry; // 使用索引替换
        }else {
            data.push(entry);
        }
        saveBodyData(data); // 保存到localStorage
        closeModal(); // 关闭弹窗
        renderDataTable(); // 刷新当前视图
    };
    // 关闭弹窗
    function closeModal() {
        document.getElementById('add-data-modal').classList.add('hidden');
    }
    /**
     * 刷新表格
     */
    function renderDataTable() {
        const year = document.getElementById('year-select').value;
        const tbody = document.getElementById('data-table-body');
        tbody.innerHTML = '';
        const data = getBodyData()
            .filter(item => item.date.startsWith(year))
            .sort((a, b) => new Date(a.date) - new Date(b.date));
        data.forEach((item, index) => {
            const tr = document.createElement('tr');
            tr.innerHTML = `
              <td>${item.date}</td>
              <td>${item.weight}</td>
              <td>${item.chest}</td>
              <td>${item.arm}</td>
              <td>${item.waist}</td>
              <td>${item.hip}</td>
              <td>${item.thigh}</td>
              <td>${item.calf}</td>
              <td><span class="delete-row" onclick="openEditModal(${index})">✏️</span>&nbsp;&nbsp;&nbsp;&nbsp;<span class="delete-row" onclick="deleteBodyData(${index})">🗑️</span></td>
            `;
            tbody.appendChild(tr);
        });
    }
    /**
     * 根据索引删除数据
     */
    function deleteBodyData(index) {
        if (confirm('确定要删除这条数据吗？')) {
            const data = getBodyData();
            data.splice(index, 1);
            saveBodyData(data);
            renderDataTable();
        }
    }
    /**
     * 清除localStorage里的数据
     */
    function clearData(){
        if (Object.keys(getBodyData()).length === 0) {
            messageplugin({ message: "当前没有身体数据，无需删除。", type: "warning" });
            return;
        }
        const confirmed = confirm(
            `是否清除全部身体数据？\n\n` +
            `⚠️ 此操作不可恢复！清除之前请先将数据导出！`
        );
        if (confirmed){
            // 清除全部数据
            localStorage.setItem(BODY_DATA_KEY, []);
            renderDataTable();
            messageplugin({ message: "身体数据已全部清除！", type: "success" });
        }
    }
    /**
     * 导出excel数据
     */
    function exportExcel() {
        // 1. 准备数据（转换为表格行）
        const worksheetData = [];
        // 添加表头
        worksheetData.push(['日期', '体重 (kg)', '胸围 (cm)', '臂围 (cm)', '腰围 (cm)', '臀围 (cm)','大腿围 (cm)','小腿围 (cm)']);
        let bodyData = getBodyData();
        for (const index in bodyData) {
            var data = bodyData[index];
            worksheetData.push([
                data.date,
                data.weight,
                data.chest,
                data.arm,
                data.waist,
                data.hip,
                data.thigh,
                data.calf
            ]);
        }
        // 2. 使用 XLSX 创建工作簿和工作表
        const workbook = XLSX.utils.book_new();
        const worksheet = XLSX.utils.aoa_to_sheet(worksheetData);
        // 3. 设置列宽（可选）
        worksheet['!cols'] = [
            { wch: 15 }, // 日期
            { wch: 15 }, // 运动计划
            { wch: 15 }, // 运动内容
            { wch: 15 }, // 每项运动时长
            { wch: 15 }, // 休息时长
            { wch: 15 }, // 总运动时长
            { wch: 15 }, // 平均心率
            { wch: 15 } // 最大心率
        ];
        // 4. 将工作表添加到工作簿
        XLSX.utils.book_append_sheet(workbook, worksheet, '身体数据');
        // 5. 导出文件
        XLSX.writeFile(workbook, `身体数据_${new Date().toISOString().slice(0, 10)}.xlsx`);
        // exportJson();
    }

    // 页面初始化
    window.onload = function () {
        initYearSelect();
        renderDataTable();
        // 添加按钮
        document.getElementById('add-data-btn').onclick = openAddModal;
        document.querySelector('#add-data-modal .close-btn').onclick = closeModal;
    };
</script>
</body>
</html>